import Stomp from 'stompjs'
import store from '@/store'
import vueConfig from '../../vue.config'

let client = null

export const disconnect = () => {
  if (client) {
    client.disconnect(function () {
      console.log('See you next time!')
    })
    client = null
  }
}

export const connect = () => {
  let uri = ''
  if (process.env.NODE_ENV === 'production') {
    // 正式环境地址的话 可以 写死 也可以按环境 然后在服务器上用ng进行代理到网关
    if (location.protocol.indexOf('https')) {
      uri = `wss://${location.hostname}/stomp/utea-stomp`
    } else {
      uri = `ws://${location.hostname}/stomp/utea-stomp`
    }
  } else {
    uri = vueConfig.devServer.proxy.replace(/^http/, 'ws') + '/stomp/utea-stomp'
  }
  if (client == null) {
    client = Stomp.client(uri)
    client.debug = false // 是否弃用调试模式
    client.connect({ token: store.state.user.token }, onConnected, onFailed)
  }
}

const onConnected = (frame) => {
// 订阅处理 后续可以自己拓展更多的订阅通道
  broadcast()
  web()
  custom()
}

const onFailed = (frame) => {
  console.log('Failed: ' + frame)
}

// const responseCallback = (frame) => {
//   console.log('得到的消息 msg=>' + frame.body)
//   console.log(frame)
//   // 接收到服务器推送消息，向服务器定义的接收消息routekey路由rk_recivemsg发送确认消息
//   client.send('/queue', {
//     'content-type': 'text/plain'
//   }, frame.body)
// }

const callBack = (frame) => {
  console.log('得到的推送消息 msg=>' + frame.body)
  console.log(frame)
}

const broadcast = () => {
  // 广播订阅
  let exchange = '/topic/utea.broadcast'
  client.subscribe(exchange, callBack)
}

const web = () => {
  // 广播订阅
  let exchange = '/queue/channel.web'
  client.subscribe(exchange, callBack)
}
const custom = () => {
  // 用户订阅
  let ui = store.getters.userInfo
  if (ui && ui.userId) {
    let exchange = '/queue/' + ui.userId + '.message'
    client.subscribe(exchange, callBack)
  }
}
